var req = require("../utils/action.js")
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatTime2 = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()

  return [year, month, day].map(formatNumber).join('-')+' '+[hour,minute].map(num).join(':')
}

const formatTime1 = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join('-')
}

function isBlank(str){
  return str == '' || str == null || str == undefined
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function getclickData(e,key){
  return e.currentTarget.dataset[key];
}

const deepClone = exports.deepClone = function e(t) {
  if (!isObject(t)) throw new Error("obj 不是一个对象！");
  var r = Array.isArray(t) ? [] : {};
  for (var n in t) r[n] = isObject(t[n]) ? e(t[n]) : t[n];
  return r;
}

//req.actions.ym+'/project/projectInfo/hello'
 function myResquest(d,_url,_success,failCount){
  wx.request({
    url: _url, //仅为示例，并非真实的接口地址
    data: d,
    method:"POST",
    header: {
      'content-type': 'application/json', // 默认值,
      'source': 'wxxcx'
    },
    success (res) {
      _success(res);
    },
    fail:function(res){
      if(!failCount){
        failCount = 2;
      }else{
        failCount++;
      }
      if(failCount <= 3){
        console.log("failCount==>"+failCount)
        setTimeout(function(){
          myResquest(d,_url,_success,failCount)
        },20)
      }
    }
  })
 }

 function getAction(d,_url,_success,failCount){
  wx.request({
    url: _url, //仅为示例，并非真实的接口地址
    data: d,
    method:"GET",
    header: {
      'content-type': 'application/json', // 默认值,
      'source': 'wxxcx'
    },
    success (res) {
      _success(res);
    },
    fail:function(res){
      if(!failCount){
        failCount = 2;
      }else{
        failCount++;
      }
      if(failCount <= 3){
        console.log("failCount==>"+failCount)
        setTimeout(function(){
          myResquest(d,_url,_success,failCount)
        },20)
      }
    }
  })
 }


 /**

 * 生成uuid

 */

const wxuuid = function () {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("").replace("-","");
  return uuid
}

function contains(arr,value){
  for(var i=0;i<arr.length;i++){
    if(arr[i] == value){
      return true;
    }
  }
  return false;
}

function remove(arr,value){
  for(var i=0;i<arr.length;i++){
    if(arr[i] == value){
      arr[i] = ""
      break;
    }
  }
  let arr2 = []
  for(var i=0;i<arr.length;i++){
    if(arr[i]){
      arr2.push(arr[i])
    }
  }
  return arr2
}

function removeIndex(arr,index){
  for(var i=index;i<arr.length-1;i++){
    arr[i] =  arr[i+1]
  }
  arr.pop()
  return arr
}

function quchong(arr){
  console.log(arr)
  var tempArr = []; //返回的值
  var indexArr= []; //返回的索引
    for (var i = 0; i < arr.length; i++) {
      if (tempArr.indexOf(arr[i]) == -1) {
        tempArr.push(arr[i]);
        indexArr.push(i)
      } else if (tempArr.indexOf(arr[i])>=0){
        for(var j = 0;j<tempArr.length;j++){
        if (tempArr[j] == arr[i]) {
          tempArr.splice(j, 1, tempArr[j]);
          indexArr.splice(j, 1, i);
        }
      }
    }
  }
  return tempArr
}


//上传图片
function uploadImage(count,_url,imageType,callback) {
  var that = this;
  wx.chooseImage({
    count: count,  //最多可以选择的图片总数
    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths;
      //启动上传等待中...

      console.log(tempFilePaths)
      
      //callback(tempFilePaths)
      wx.showLoading({title: '上传中...'})
      console.log(_url)
      wx.setStorageSync('imageUploadCount', 0)
      let n = tempFilePaths.length
      for(var i=0;i<n;i++){
        console.log("iii-->"+i)
        upload(_url,tempFilePaths,imageType,1,i,callback)
      }
      
    }
  });
}

function savePiture(_url,tempFilePaths,imageType,callback){
  let n = tempFilePaths.length
  for(var i=0;i<n;i++){
    //console.log("iii-->"+i)
    upload(_url,tempFilePaths[i],imageType,1,callback)
  }
}

function upload(_url,tempFilePath,imageType,failCount,callback){
 // console.log("i:"+_url)
  wx.uploadFile({
    url: _url,
    filePath: tempFilePath,
    name: 'file',
    formData: {type:imageType},
    header: {"Content-Type": "multipart/form-data"},
    success: function (res) {
      //let successCount = wx.getStorageSync('imageUploadCount')
      //successCount++;
      var data = JSON.parse(res.data);
      //console.log("successCount:"+successCount+"===>"+tempFilePaths.length)
      //if(successCount == tempFilePaths.length){
      //  wx.hideLoading()
     //   wx.setStorageSync('imageUploadCount', 0)
      //}else{
      //  wx.setStorageSync('imageUploadCount', successCount)
      //}
      callback(data.imagePath)
      //callback(data)
    },
    fail: function (res) {
      console.log(res)
      console.log("failCount==>"+failCount)
      if(!failCount){
        failCount = 2;
      }else{
        failCount++;
      }
      if(failCount <= 3){
        console.log("failCount==>"+failCount)
        setTimeout(function(){
          upload(_url,tempFilePath,imageType,failCount,callback)
          //myResquest(d,_url,_success,failCount)
        },20)
      }else{
        wx.setStorageSync('imageUploadCount', 0)
        wx.hideLoading()
        wx.showModal({
          title: '错误提示',
          content: '上传图片失败,请重新上传',
          showCancel: false,
          success: function (res) { }
        })
        callback('fail')
      }
      
    }
  })
}

function addArr(originArr,arr){
  for(let i=0;i<arr.length;i++){
    originArr.push(arr[i])
  }
  return originArr
}

module.exports = {
  formatTime2:formatTime2,
  formatTime: formatTime,
  deepClone:deepClone,
  getclickData:getclickData,
  myResquest:myResquest,
  getAction:getAction,
  wxuuid:wxuuid,
  isBlank:isBlank,
  quchong:quchong,
  contains:contains,
  remove:remove,
  addArr:addArr,
  uploadImage:uploadImage,
  savePiture:savePiture,
  removeIndex:removeIndex,
  upload:upload
}
